<?php

namespace App\Http\Middleware;

use App\Enum\CodeEnum;
use App\Enum\ThirdEnum;
use App\Lib\Jwt;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CheckThird
{
    private const PLATFORM_NONE='NOWAYS';

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //1.拿到token
        $token = $request->bearerToken();
        $platformCode = $request->header('Platform-Code', self::PLATFORM_NONE);
        if (empty($token)) {
            return fail(CodeEnum::SIGN_ERROR, 'token不存在');
        }

        if( $platformCode !== ThirdEnum::THIRD_PLATFORM_TEST_CODE ) {
            try {
                // 获取平台ID
                $platform = $this->_getPlatformInfo($platformCode);
                $platformId = $platform[0];
                $secretKey = $platform[1];
            } catch (\Exception $e) {
                return fail(CodeEnum::SIGN_ERROR, '验证失败：无法获取账号。');
            }
            try {
                //验证token
                $result = Jwt::decodeThirdToken($token, $secretKey);
                $decodePlatformCode = $result['platform-code'];
                if ($decodePlatformCode === $platformCode) {
                    if ((time() > $result['expire']) || ($result['expire'] - time()) > env('THIRD_PLATFORM_TOKEN_EXPIRE',ThirdEnum::R_PLATFORM_JWT_EXPIRE_IN))
                        return fail(CodeEnum::SIGN_ERROR, '验证失败：token过期。');
                    $request->platformId = $platformId;
                } else {
                    return fail(CodeEnum::SIGN_ERROR, '验证失败：不匹配。');
                }

            } catch (\Exception $e) {
                return fail(CodeEnum::SIGN_ERROR, 'token失效');
            }
        }else{
            Log::notice("模拟进入 third".$token);
            $request->platformId = $token;
        }
        Log::notice(sprintf('验证通过。平台ID=%d,CODE=%s,URL=%s', $request->platformId, $platformCode, $request->path()));

        return $next($request);
    }
    private function _getPlatformInfo($platformCode){
        if( empty($platformCode)
            || ($platformCode === self::PLATFORM_NONE)
            || strlen($platformCode) != ThirdEnum::PLATFORM_CODE_LENGTH
            || !in_array( $platformCode, array_keys(ThirdEnum::THIRD_PLATFORMS))
        ){
            return fail(CodeEnum::SIGN_ERROR, '账号异常');
        }

        return ThirdEnum::THIRD_PLATFORMS[$platformCode];
    }
}

